import React, { useState } from "react";
import config from "../../../config/config";
import * as settingService from '../services/settingService';
import defaultSetting from "../components/setting/DefaultSetting";
import { message } from 'antd';
import {onSaveUser} from "../services/settingService";

export default function useSettingState() {

    const [ollamaModels, setOllamaModels] = useState([]);
    const [systemSetting, setSystemSetting] = useState([]);
    const [settingItemMap, setSettingItemMap] = useState({});

    const loadOllamaModels = () => {
        fetch(`${config.api.home.ollamaModelList}`).then(res => res.json()).then(res => setOllamaModels(res.data));
    }

    const loadSettingItem = (params) => {
        settingService.getSettingList(params).then(res => {
            if (res.code == 200) {
                let settingObj = {};
                let settingItems = res.data;
                setSystemSetting(settingItems);

                let defaultSettingItem = defaultSetting.default_setting[params["source"]];
                let defaultSettingKeys = Object.keys(defaultSettingItem);
                for (let i = 0; i < defaultSettingKeys.length; i++) {
                    let key = defaultSettingKeys[i];
                    let itemObj = settingItems.find(item => item.name == key);
                    if (itemObj && itemObj.content) {
                        settingObj[key] = itemObj.content;
                    } else {
                        settingObj[key] = defaultSettingItem[key];
                    }
                }
                setSettingItemMap(settingObj);
            }
        });
    }

    const onSaveSetting = (values) => {
        settingService.saveSettingItem(values).then(res => {
            if (res.code == 200) {
                message.success("保存成功");
            }
        });
    }

    const onSaveUser = (user) => {
        settingService.onSaveUser(user).then(res => {
            if (res.code == 200) {
                message.success("保存成功");
            }
        });
    }

    return { ollamaModels, loadOllamaModels, loadSettingItem, settingItemMap, onSaveSetting, onSaveUser };
}
